{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 95,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"A very simple MNIST classifier.\n",
    "See extensive documentation at https://www.tensorflow.org/get_started/mnist/beginners\n",
    "\"\"\"\n",
    "\n",
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "from tensorflow.examples.tutorials.mnist import input_data"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们在这里调用系统提供的 MNIST 数据函数为我们读入数据，如果没有下载的话则进行下载。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting data\\train-images-idx3-ubyte.gz\n",
      "Extracting data\\train-labels-idx1-ubyte.gz\n",
      "Extracting data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting data\\t10k-labels-idx1-ubyte.gz\n"
     ]
    }
   ],
   "source": [
    "# Import data\n",
    "#data_dir = '/tmp/tensorflow/mnist/input_data'\n",
    "#本地数据目录\n",
    "data_dir = 'data'\n",
    "mnist = input_data.read_data_sets(data_dir, one_hot=True)\n",
    "def initialize(shape, stddev=0.1):\n",
    "  return tf.truncated_normal(shape, stddev=stddev)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "一个非常非常简陋的模型"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 97,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Create the model\n",
    "l1_unit_count=100\n",
    "x = tf.placeholder(tf.float32, [None, 784])\n",
    "init_learning_rate = tf.placeholder(tf.float32)\n",
    "epoch_steps = tf.to_int64(tf.div(60000, tf.shape(x)[0]))\n",
    "global_step = tf.train.get_or_create_global_step()\n",
    "current_epoch = global_step//epoch_steps\n",
    "decay_times = current_epoch \n",
    "#此处W不能用零矩阵\n",
    "#W = tf.Variable(tf.zeros([784, 10]))\n",
    "W1 = tf.Variable(initialize([784,l1_unit_count],np.sqrt(2/784)))\n",
    "#b = tf.Variable(tf.zeros([10]))\n",
    "b1=tf.Variable(tf.constant(0.001, shape=[l1_unit_count]))\n",
    "logist1 = tf.matmul(x, W1) + b1\n",
    "y1 = tf.nn.relu(logist1)\n",
    "#y1 = tf.nn.softmax(logist1)\n",
    "'''\n",
    "增加一个隐层\n",
    "'''\n",
    "l2_unit_count =10\n",
    "W2 = tf.Variable(initialize([l1_unit_count,l2_unit_count],np.sqrt(2/784)))\n",
    "b2= tf.Variable(tf.constant(0.001, shape=[l2_unit_count]))\n",
    "logist2 = tf.matmul(y1,W2) + b2\n",
    "#如果用交叉熵，这里不需要经过激活函数\n",
    "#y2 = tf.nn.relu(logist2)\n",
    "y2 = logist2\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "定义我们的 ground truth 占位符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 98,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Define loss and optimizer\n",
    "y_ = tf.placeholder(tf.float32, [None, 10])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "接下来我们计算交叉熵，注意这里不要使用注释中的手动计算方式，而是使用系统函数。\n",
    "另一个注意点就是，softmax_cross_entropy_with_logits 的 logits 参数是**未经激活的 wx+b**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 99,
   "metadata": {},
   "outputs": [],
   "source": [
    "# The raw formulation of cross-entropy,\n",
    "#\n",
    "#   tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.nn.softmax(y)),\n",
    "#                                 reduction_indices=[1]))\n",
    "#\n",
    "# can be numerically unstable.\n",
    "#\n",
    "# So here we use tf.nn.softmax_cross_entropy_with_logits on the raw\n",
    "# outputs of 'y', and then average across the batch.\n",
    "cross_entropy = tf.reduce_mean(\n",
    "    tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y2)\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "生成一个训练step"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "metadata": {},
   "outputs": [],
   "source": [
    "l2_loss = tf.nn.l2_loss(W1) + tf.nn.l2_loss(W2)\n",
    "total_loss = cross_entropy + 4e-5*l2_loss\n",
    "current_learning_rate = tf.multiply(init_learning_rate, \n",
    "                                    tf.pow(0.575, tf.to_float(decay_times)))\n",
    "optimizer = tf.train.AdamOptimizer(current_learning_rate)\n",
    "gradients = optimizer.compute_gradients(total_loss)\n",
    "train_step = optimizer.apply_gradients(gradients)\n",
    "train_step = tf.train.AdamOptimizer(current_learning_rate).minimize(total_loss,global_step=global_step)\n",
    "correct_prediction = tf.equal(tf.argmax(y2, 1), tf.argmax(y_, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "sess = tf.Session()\n",
    "#sess = tf.InteractiveSession()\n",
    "init_op = tf.global_variables_initializer()\n",
    "sess.run(init_op)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在这里我们仍然调用系统提供的读取数据，为我们取得一个 batch。\n",
    "然后我们运行 3k 个 step (5 epochs)，对权重进行优化。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "step=0\n",
      "0.385\n",
      "step=100\n",
      "0.9275\n",
      "step=200\n",
      "0.9437\n",
      "step=300\n",
      "0.9494\n",
      "step=400\n",
      "0.9508\n",
      "step=500\n",
      "0.9608\n",
      "step=600\n",
      "0.9602\n",
      "step=700\n",
      "0.9631\n",
      "step=800\n",
      "0.9687\n",
      "step=900\n",
      "0.9666\n",
      "step=1000\n",
      "0.9698\n",
      "step=1100\n",
      "0.9711\n",
      "step=1200\n",
      "0.9708\n",
      "step=1300\n",
      "0.9747\n",
      "step=1400\n",
      "0.9744\n",
      "step=1500\n",
      "0.9744\n",
      "step=1600\n",
      "0.977\n",
      "step=1700\n",
      "0.9743\n",
      "step=1800\n",
      "0.9744\n",
      "step=1900\n",
      "0.9767\n",
      "step=2000\n",
      "0.978\n",
      "step=2100\n",
      "0.9774\n",
      "step=2200\n",
      "0.9775\n",
      "step=2300\n",
      "0.9786\n",
      "step=2400\n",
      "0.9805\n",
      "step=2500\n",
      "0.9795\n",
      "step=2600\n",
      "0.9791\n",
      "step=2700\n",
      "0.9793\n",
      "step=2800\n",
      "0.9801\n",
      "step=2900\n",
      "0.9804\n"
     ]
    }
   ],
   "source": [
    "# Train\n",
    "for step in range(3000):\n",
    "    batch_xs, batch_ys = mnist.train.next_batch(100)\n",
    "    #sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\n",
    "    lr = 1e-2\n",
    "    _, loss, l2_loss_value, total_loss_value, current_lr_value = \\\n",
    "        sess.run(\n",
    "               [train_step, cross_entropy, l2_loss, total_loss, \n",
    "                current_learning_rate], \n",
    "               feed_dict={x: batch_xs, y_: batch_ys, \n",
    "                          init_learning_rate:lr})\n",
    "    # Test trained model\n",
    "    if step %100 == 0:\n",
    "        correct_prediction = tf.equal(tf.argmax(y2, 1), tf.argmax(y_, 1))\n",
    "        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "        print(\"step=%d\" % step)\n",
    "        print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))\n",
    "sess.close()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "验证我们模型在测试数据上的准确率"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "毫无疑问，这个模型是一个非常简陋，性能也不理想的模型。目前只能达到 92% 左右的准确率。\n",
    "接下来，希望大家利用现有的知识，将这个模型优化至 98% 以上的准确率。\n",
    "Hint：\n",
    "- 多隐层\n",
    "- 激活函数\n",
    "- 正则化\n",
    "- 初始化\n",
    "- 摸索一下各个超参数\n",
    "  - 隐层神经元数量\n",
    "  - 学习率\n",
    "  - 正则化惩罚因子\n",
    "  - 最好每隔几个 step 就对 loss、accuracy 等等进行一次输出，这样才能有根据地进行调整"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
